using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace MultiTCPProxy.Services
{
    /// <summary>
    /// 进程守护类，用于监控和重启服务
    /// </summary>
    public class ProcessGuardian
    {
        private static readonly ProcessGuardian _instance = new ProcessGuardian();
        private readonly CancellationTokenSource _cancellationTokenSource;
        private Task _monitorTask;
        private bool _isMonitoring;

        public static ProcessGuardian Instance => _instance;

        private ProcessGuardian()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            DebugLogger.Log("进程守护初始化完成");
        }

        /// <summary>
        /// 启动进程监控
        /// </summary>
        public void StartMonitoring()
        {
            if (_isMonitoring)
            {
                DebugLogger.Log("进程监控已经在运行中", LogLevel.Warning);
                return;
            }

            _isMonitoring = true;
            DebugLogger.Log("开始进程监控");

            _monitorTask = Task.Run(async () =>
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    try
                    {
                        // 检查服务进程是否存在
                        if (!IsServiceProcessRunning())
                        {
                            DebugLogger.Log("检测到服务进程不存在，准备重启");
                            // 重启服务
                            RestartService();
                        }

                        // 每5秒检查一次
                        await Task.Delay(5000, _cancellationTokenSource.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        DebugLogger.Log("进程监控被取消");
                        break;
                    }
                    catch (Exception ex)
                    {
                        DebugLogger.LogException(ex, "进程监控异常");
                    }
                }
            }, _cancellationTokenSource.Token);
        }

        /// <summary>
        /// 停止进程监控
        /// </summary>
        public void StopMonitoring()
        {
            if (!_isMonitoring)
            {
                DebugLogger.Log("进程监控未在运行", LogLevel.Warning);
                return;
            }

            DebugLogger.Log("正在停止进程监控");
            _cancellationTokenSource.Cancel();
            _monitorTask?.Wait();
            _isMonitoring = false;
            DebugLogger.Log("进程监控已停止");
        }

        /// <summary>
        /// 检查服务进程是否在运行
        /// </summary>
        private bool IsServiceProcessRunning()
        {
            try
            {
                Process[] processes = Process.GetProcessesByName("MultiTCPProxy");
                bool isRunning = processes.Length > 0;
                DebugLogger.Log($"服务进程状态检查: {(isRunning ? "运行中" : "未运行")}", LogLevel.Debug);
                return isRunning;
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "检查服务进程状态时发生错误");
                return false;
            }
        }

        /// <summary>
        /// 重启服务
        /// </summary>
        private void RestartService()
        {
            try
            {
                DebugLogger.Log("正在重启服务");
                // 启动新的服务进程
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = Process.GetCurrentProcess().MainModule.FileName,
                    Arguments = "start",
                    UseShellExecute = true,
                    Verb = "runas" // 以管理员权限运行
                };

                Process.Start(startInfo);
                DebugLogger.Log("服务重启命令已发送");
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "重启服务失败");
            }
        }
    }
} 